﻿using Microsoft.SharePoint;
using Repo.Enums;

namespace Repo.DataAccess
{
    public class KeyGenerator
    {
        #region Public

        public static string GenerateKey(string contentTypeName, string listTitle)
        {
            var user = GetUser();
            return GenerateKey(user, contentTypeName, listTitle);
        }

        public static string GenerateKey(string user, string contentTypeName, string listTitle)
        {
            var key = user + ";" + contentTypeName + ";" + listTitle;
            return key;
        }

        public static string GetUserFromKey(string key)
        {
            return GetValueFromSplit(key, 0);
        }

        public static string GetContentTypeFromKey(string key)
        {
            return GetValueFromSplit(key, 1);
        }

        public static string GetListFromKey(string key)
        {
            return GetValueFromSplit(key, 2);
        }
        
        #endregion

        #region Private

        private static string GetUser()
        {
            SPUser currentUser = null;
            if (SPContext.Current != null
                && SPContext.Current.Web != null
                && SPContext.Current.Web.CurrentUser != null)
            {
                currentUser = SPContext.Current.Web.CurrentUser;
            }
            return currentUser != null ? UserType.Authenticated.ToString() : UserType.Anonymous.ToString();
        }

        private static string GetValueFromSplit(string key, int index)
        {
            var splitKey = key.Split(';');
            if (index < splitKey.Length)
            {
                return splitKey[index];
            }
            return null;
        }
        
        #endregion
    }
}
